<template>
	<view class="cu-modal bottom-modal" :class="{ show: showAuth }" @tap="closeAuthModal" style="z-index: 10080;">
		<view class="login-wrap cu-dialog form-wrap  safe-area-inset-bottom" @tap.stop
			style="border-radius: 20rpx 20rpx 0 0;">
			<!-- 1.账号密码登录 -->
			<view v-if="authType === 'accountLogin'">
				<view class="head-box u-m-b-60 u-flex-col ">
					<view class="u-flex u-m-b-20">
						<view class="head-title u-m-r-40 head-title-animation">账号登录</view>
						<view class="head-title-active head-title-line" @tap="showAuthModal('smsLogin')">
							短信登录
						</view>
					</view>
					<view class="head-subtitle">如果未设置过密码，请点击忘记密码</view>
				</view>
				<view class="form-item  u-border-bottom ">
					<view class="item-content u-flex u-col-center">
						<view class="item-title">账号</view>
						<u-input class="u-m-r-10 u-flex-1" placeholder="请输入账号" @blur="checkValue($event, 'account')"
							@input="checkValue($event, 'account')" :placeholderStyle="placeholderStyle"
							v-model="form['accountLogin'].data.account" type="text"></u-input>
						<button class="u-reset-button forgot-btn" @tap="showAuthModal('forgotPwd')">
							忘记密码
						</button>
					</view>
					<view class="message-error">
						{{ form["accountLogin"].error.account || "" }}
					</view>
				</view>
				<view class="form-item u-border-bottom">
					<view class="item-content u-flex u-col-center">
						<view class="item-title">密码</view>
						<u-input class="u-m-r-10 u-flex-1" placeholder="请输入密码" :placeholderStyle="placeholderStyle"
							v-model="form['accountLogin'].data.password" type="password"
							@blur="checkValue($event, 'password')" @input="checkValue($event, 'password')"></u-input>
						<button class="u-reset-button login-btn-start" :style="{'background':'linear-gradient(174deg, ' + $CHANGEA + ' 0%, ' + $COLOR + ' 100%)'}" @tap="accountLoginSubmit">
							登录
						</button>
					</view>
					<view class="message-error">
						{{ form["accountLogin"].error.password || "" }}
					</view>
				</view>
				<button class="u-reset-button type-btn">
					<!-- 立即注册 -->
				</button>
			</view>

			<!-- 2.短信登录 -->
			<view v-if="authType === 'smsLogin'">
				<view class="head-box u-m-b-60">
					<view class="u-flex u-m-b-20">
						<view class="head-title-active u-m-r-40" @tap="showAuthModal('accountLogin')">
							账号登录
						</view>
						<view class="head-title  head-title-animation">
							短信登录
						</view>
					</view>
					<!-- <view class="head-subtitle">未注册手机号请先点击下方立即注册</view> -->
				</view>
				<view class="form-item u-border-bottom">
					<view class="item-content u-flex u-col-center">
						<view class="item-title">手机号</view>
						<u-input class="u-m-r-10 u-flex-1" placeholder="请输入手机号" @blur="checkValue($event, 'mobile')"
							@input="mobileInput($event, 'mobile')" :placeholderStyle="placeholderStyle"
							v-model="form['smsLogin'].data.mobile" type="number"></u-input>
						<button class="u-reset-button code-btn code-btn-start"
							:disabled="!form['smsLogin'].data.isMobileEnd"
							:class="{ 'code-btn-end': form['smsLogin'].data.isMobileEnd }"
							:style="'border: 1rpx solid '+$COLOR+';color: '+$COLOR+';background-color:#fff'"
							@tap="getSmsCode('mobilelogin')">
							{{ codeText }}
						</button>
					</view>
					<view class="message-error">{{ form["smsLogin"].error.mobile || "" }}</view>
				</view>
				<view class="form-item u-border-bottom">
					<view class="item-content u-flex u-col-center">
						<view class="item-title">验证码</view>
						<u-input class="u-m-r-10 u-flex-1" @blur="checkValue($event, 'code')"
							@input="checkValue($event, 'code')" placeholder="请输入验证码"
							:placeholderStyle="placeholderStyle" v-model="form['smsLogin'].data.code"
							type="number"></u-input>
						<button class="u-reset-button login-btn-start" :style="{'background':'linear-gradient(174deg, ' + $CHANGEA + ' 0%, ' + $COLOR + ' 100%)'}" @tap="smsLoginSubmit">
							登录
						</button>
					</view>
					<view class="message-error">{{ form["smsLogin"].error.code || "" }}</view>
				</view>
				<button class="u-reset-button type-btn">
					<!-- 立即注册 -->
				</button>
			</view>
			<!-- 5.绑定手机号 -->
		<!-- 	<view v-if="authType === 'bindMobile'">
				<view class="head-box u-m-b-60">
					<view class="head-title u-m-b-20">绑定手机号</view>
					<view class="head-subtitle">为了您的账号安全，请绑定手机号</view>
				</view>
				<view class="form-item u-border-bottom">
					<view class="item-content u-flex u-col-center">
						<view class="item-title">手机号</view>
						<u-input class="u-m-r-10 u-flex-1" @blur="checkValue($event, 'mobile')"
							@input="mobileInput($event, 'mobile')" placeholder="请输入手机号"
							:placeholderStyle="placeholderStyle" v-model="form['bindMobile'].data.mobile"
							type="number"></u-input>
						<button class="u-reset-button code-btn code-btn-start"
							:disabled="!form['bindMobile'].data.isMobileEnd"
							:class="{ 'code-btn-end': form['bindMobile'].data.isMobileEnd }"
							@tap="getSmsCode('changemobile')">
							{{ codeText }}
						</button>
					</view>
					<view class="message-error">{{ form["bindMobile"].error.mobile || "" }}</view>
				</view>
				<view class="form-item u-border-bottom">
					<view class="item-content u-flex u-col-center">
						<view class="item-title">验证码</view>
						<u-input class="u-m-r-10 u-flex-1" @blur="checkValue($event, 'code')"
							@input="checkValue($event, 'code')" placeholder="请输入验证码"
							:placeholderStyle="placeholderStyle" v-model="form['bindMobile'].data.code"
							type="number"></u-input>
						<button class="u-reset-button login-btn-start" @tap="bindMobileSubmit">
							立即绑定
						</button>
					</view>
					<view class="message-error">{{ form["bindMobile"].error.code || "" }}</view>
				</view>
			</view> -->

			<!-- 第三方登录 -->
			<view v-if="authType === 'accountLogin' || authType === 'smsLogin'"
				class="auto-login-box u-flex u-row-center u-col-center">
				<!-- 微信 -->
			<!-- 	<button v-if="['App', 'wxOfficialAccount', 'wxMiniProgram'].includes(platform)" class="u-reset-button"
					open-type="getPhoneNumber" @getphonenumber="thirdLogin('wechat', $event)"
					@tap="thirdLogin('wechat')">
					<image class="auto-login-img" :src="$IMAGE_URL + '/auto_login_wx.png'"></image>
				</button> -->
				<!-- 支付宝 -->
			<!-- 	<image
					v-if="['App', 'alipayMiniProgram', 'H5'].includes(platform)"
					class="auto-login-img"
					@tap="thirdLogin('alipay')"
					:src="$IMAGE_URL + '/auto_login_ali.png'"
					mode=""
				></image> -->
				<!-- 苹果 -->
				<!-- #ifdef APP-PLUS -->
			<!-- 	<image v-if="device === 'ios'" class="auto-login-img" @tap="thirdLogin('apple')"
					:src="$IMAGE_URL + '/auto_login_iphone.png'"></image> -->
				<!-- #endif -->
			</view>

			<!-- 协议 -->
			<view v-if="['accountLogin', 'smsLogin'].includes(authType)"
				class="agreement-box u-flex u-row-center">
				<u-checkbox v-model="protocol" shape="circle" :active-color="$COLOR">
					<view class="agreement-text tcp-text u-flex u-col-center">
						我已阅读并遵守
						<view class="tcp-text u-flex u-col-center" :style="{color: $COLOR}">
							<view @tap.stop="
								$Router.push({
									path: '/pages/user/agreementList/userRegis'
								})
							">
								《用户协议》
							</view>
							与
							<view @tap.stop="
									$Router.push({
										path: '/pages/user/agreementList/userPriva'
									})
							">
								《隐私协议》
							</view>
						</view>
					</view>
				</u-checkbox>
			</view>
		</view>
	</view>
</template>

<script>
/**
 * 登录提示页
 */
import FormValidate from "@/shopro/validate/form";
import schema from "@/uview-ui/libs/util/async-validator";
import wechat from "@/shopro/wechat/wechat";
import { mapMutations, mapActions, mapState, mapGetters } from "vuex";
// #ifdef APP-PLUS
import apple from "@/shopro/apple";
import { startAlipayAuth } from '@/ap-config.js';
// #endif

export default {
	name: "shoproAuthModal",
	data() {
		return {
			platform: this.$platform.get(),
			device: this.$platform.device(),
			form: {
				// 1.账号密码登录
				accountLogin: {
					data: {
						account: "", // 账号
						password: "" // 密码
					},
					rules: {
						account: FormValidate.account,
						password: FormValidate.password
					},
					error: {
						account: "",
						password: ""
					}
				},

				// 2.短信登录
				smsLogin: {
					data: {
						mobile: "", // 手机号
						code: "", // 验证码
						isMobileEnd: false // 手机号输入完毕
					},
					rules: {
						code: FormValidate.code,
						mobile: FormValidate.mobile
					},
					error: {
						mobile: "", // 手机号
						code: "" // 验证码
					}
				},
			},
			loginIdentification:true,
			codeText: "获取验证码",
			disabledCode: false,
			protocol: false, //是否同意隐私协议
			placeholderStyle: "font-size: 30rpx; font-weight: 500;color:#C2C7CF;",
			loginShow:false,
		};
	},

	computed: {
		...mapGetters(["initShop", "isLogin", "authType"]),
		showAuth: {
			get() {
				return !!this.authType;
			},
			set(value) {
				value ? uni.hideTabBar() : uni.showTabBar();
			}
		}
	},
	mounted() { },
	created() {
		// this.$http(
		// 		"user.appPhoneLogin",
		// 		{
		// 			phone:19106577139,
		// 		},
		// 		"登录中..."
		// 	)
		// 	.then(res => {
		// 		if (res.code === 200) {
		// 			this.getUserInfo(res.data.token);
		// 			this.$u.toast(res.msg);
		// 		} else {
		// 			this.$u.toast(res.msg);
		// 		}
		// 	});
		// this.login()
	},
	methods: {
		...mapActions(["getUserInfo", "showAuthModal"]),
		// 检测
		checkValue(e, key) {
			this.validation(key);
		},

		// 校验数据
		validation(key, callback = () => { }) {
			let that = this;
			//拿到需要校验的数据
			let fieldValue = this.form[this.authType].data[key];
			//拿到需要检验的规则
			let rules = this.form[this.authType].rules[key];
			// 判空
			if (!rules || rules.length === 0) {
				return callback("");
			}
			// 设置当前的装填，标识为校验中
			let validateState = "validating";
			// 调用async-validator的方法
			let validator = new schema({
				[key]: rules
			});
			// 校验
			validator.validate(
				{
					[key]: fieldValue
				},
				{
					firstFields: true
				},
				(errors, fields) => {
					// 记录状态和报错信息
					validateState = !errors ? "success" : "error";
					let validateMessage = errors ? errors[0].message : "";
					that.form[that.authType].error[key] = validateMessage;
					callback(validateMessage);
				}
			);
		},

		// 校验全部数据
		validateAll(callback) {
			let that = this;
			return new Promise(resolve => {
				// 对当前所有表单检验
				let valid = true; // 默认通过
				let count = 0; // 用于标记是否检查完毕
				let errorArr = []; // 存放错误信息
				let curFormData = that.form[that.authType].data;
				Object.keys(curFormData).map(field => {
					that.validation(field, error => {
						// 如果回调有error
						if (error) {
							valid = false;
							errorArr.push(error);
						}
						if (++count === Object.keys(curFormData).length) {
							resolve(valid);
							if (errorArr.length) {
								this.$u.toast(errorArr[0]);
							}
							if (typeof callback == "function") callback(valid);
						}
					});
				});
			});
		},

		// 手机号是否输入完毕
		mobileInput(e, key) {
			this.form[this.authType].data.isMobileEnd = this.$u.test.mobile(
				this.form[this.authType].data.mobile
			);
			this.validation(key);
		},

		closeAuthModal() {
			this.$store.dispatch("showAuthModal", "");
		},

		// 获取短信验证码
		getSmsCode(type) {
			const that = this;
			if (that.form[this.authType].data.isMobileEnd && !that.disabledCode) {
				console.log('发送验证码',that.form[this.authType].data.mobile)
				that.$http(
					"user.smsSend",
					{
						phone: that.form[this.authType].data.mobile,
					},
					"获取验证码中..."
				).then(res => {
					if (res.code === 200) {
						that.codeChange();
						that.$u.toast("验证码已发送，请注意查收短信");
					} else {
						that.$u.toast(res.msg);
					}
				});
			} else {
				that.$u.toast("请稍后再试");
			}
		},

		// 倒计时
		codeChange() {
			if (this.disabledCode) return;
			this.disabledCode = true;
			let n = 60;
			this.codeText = n + "s";
			const run = setInterval(() => {
				n -= 1;
				if (n < 0) {
					clearInterval(run);
				}
				this.codeText = n + "s";
				if (this.codeText < 0 + "s") {
					this.disabledCode = false;
					this.codeText = "重新获取";
				}
			}, 1000);
		},

		// 规则校验
		validateSubmit() {
			if (
				["accountLogin", "smsLogin"].includes(this.authType) &&
				!this.protocol
			) {
				this.$u.toast("请同意用户协议");
				return false;
			}
			return this.validateAll();
		},
	// 	 authLogin() {
	// 		uni.navigateToMiniProgram({
	// 		  appId: '2021004105606199',
	// 		  path: 'https://authweb.alipay.com/auth?auth_type=PURE_OAUTH_SDK&app_id='+ this.$APP_ID +'&scope=auth_user&state=init',
	// 		  extraData: {
	// 			// 需要传递的参数
	// 		  },
	// 		  success(res) {
	// 			console.log('跳转成功')
	// 			console.log(res)
	// 		  },
	// 		  fail(error) {
	// 			console.log('跳转失败')
	// 		  }
	// 		})
	
	// 	},
		// 第三方登录
		async thirdLogin(provider, payload = null) {
			if (this.platform === 'wxMiniProgram' && payload === null) return;
			if (!this.protocol) {
				this.$u.toast("请同意用户协议");
				return false;
			}
			console.log('支付宝登录',this.$APP_ID)
			
			let urls = 'https://authweb.alipay.com/auth?auth_type=PURE_OAUTH_SDK&app_id='+ this.$APP_ID +'&scope=auth_user&state=6LeD55ub56ef5py6YXNkc2FkcXdkZGFzY3hjcXdlcWVxZXFxZXE='
			urls=encodeURIComponent(urls);//将地址编码成浏览器访问的格式
			// 判断平台
			if (plus.os.name == 'Android') {
				// uni.redirectTo({
				// 	url:urls
				// })
			  plus.runtime.openURL(
			    'alipays://platformapi/startapp?appId=20000067&url=' + urls,
				// 'https://authweb.alipay.com/auth?auth_type=PURE_OAUTH_SDK&app_id='+ this.$APP_ID +'&scope=auth_user&state=6LeD55ub56ef5py6YXNkc2FkcXdkZGFzY3hjcXdlcWVxZXFxZXE=',
			    res => {
				//这里写打开URL地址失败后的处理
			      // uni.showModal({
			      //   content: '本机未检测到对应客户端，是否打开浏览器访问页面？',
			      //   success: function (res) {
			      //     if (res.confirm) {
			      //       //plus.runtime.openURL();
			      //     }
			      //   }
			      // });
			    },
			    'com.eg.android.AlipayGphone'
			  );
			} else if (plus.os.name == 'iOS') {
			  plus.runtime.openURL(
			    'alipay://platformapi/startapp?appId=20000067&url=' + urls,
			    res => {
			      uni.showModal({
			        content: '本机未检测到对应客户端，是否打开浏览器访问页面？',
			        success: function (res) {
			          if (res.confirm) {
			            //plus.runtime.openURL(url);
			          }
			        }
			      });
			    },
			    'com.eg.android.AlipayGphone'
			  );
			}
			
			// let alipayUrl = "apiname=com.alipay.account.auth&app_id=xxxxx&app_name=mc&auth_type=AUTHACCOUNT&biz_type=openservice&method=alipay.open.auth.sdk.code.get&pid=xxxxx&product_id=APP_FAST_LOGIN&scope=kuaijie&sign_type=RSA2&target_id=2021004105642159&sign=fMcp4GtiM6rxSIeFnJCVePJKV43eXrUP86CQgiLhDHH2u%2FdN75eEvmywc2ulkm7qKRetkU9fbVZtJIqFdMJcJ9Yp%2BJI%2FF%2FpESafFR6rB2fRjiQQLGXvxmDGVMjPSxHxVtIqpZy5FDoKUSjQ2%2FILDKpu3%2F%2BtAtm2jRw1rUoMhgt0%3D"
			// let alipayUrl="https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id=2021004105642159&scope=auth_user&redirect_uri=ENCODED_URL"  
			// let openURL="alipays://platformapi/startapp?appId=20000067&url="+encodeURIComponent(alipayUrl);  
			// console.log("openURL:" + openURL);  
			// plus.runtime.openURL(openURL,err=>{  
		
		},

		// 1.账号登录
		async accountLoginSubmit() {
			let that = this;
			(await that.validateSubmit()) &&
				that
					.$http(
						"user.accountLogin",
						{
							phone: that.form["accountLogin"].data.account,
							pwd: that.form["accountLogin"].data.password
						},
						"登录中..."
					)
					.then(res => {
						if (res.code === 200) {
							that.closeAuthModal();
							that.getUserInfo(res.data.token);
							that.$u.toast(res.msg);
						} else {
							that.$u.toast(res.msg);
						}
					});
		},

		// 2.短信登录
		async smsLoginSubmit() {
			let that = this;
			(await that.validateSubmit()) &&
				that
					.$http(
						"user.smsLogin",
						{
							phone: that.form["smsLogin"].data.mobile,
							code: that.form["smsLogin"].data.code
						},
						"登录中..."
					)
					.then(res => {
						if (res.code === 200) {
							that.closeAuthModal();
							that.getUserInfo(res.data.token);
							that.$u.toast(res.msg);
						} else {
							that.$u.toast(res.msg);
						}
					});
		},



	}
};
</script>

<style lang="scss" scoped>
@keyframes title-animation {
	0% {
		font-size: 32rpx;
	}

	100% {
		font-size: 36rpx;
	}
}

.form-wrap {
	.form-item {
		display: flex;
		flex-direction: column;
		font-size: 28rpx;
		padding: 20rpx 0;
		color: $u-main-color;
		box-sizing: border-box;
		line-height: $u-form-item-height;
		width: 100%;

		.item-title {
			width: 140rpx;
			font-size: 30rpx;
			color: #333;
			font-weight: 600;
			text-align: left;
		}

		.message-error {
			text-align: left;
			font-size: 24rpx;
			line-height: 24rpx;
			color: $u-type-error;
			margin-top: 12rpx;
			margin-left: 120rpx;
		}
	}
}

.login-wrap {
	padding: 50rpx 34rpx;
	min-height: 700rpx;
	background-color: #fff;

	.head-box {
		.head-title {
			min-width: 160rpx;
			font-size: 36rpx;
			font-weight: bold;
			color: #333333;
			line-height: 36rpx;
		}

		.head-title-active {
			width: 160rpx;
			font-size: 32rpx;
			font-weight: 600;
			color: #999;
			line-height: 36rpx;
		}

		.head-title-animation {
			animation-name: title-animation;
			animation-duration: 0.1s;
			animation-timing-function: ease-out;
			animation-fill-mode: forwards;
		}

		.head-title-line {
			position: relative;

			&::before {
				content: "";
				width: 1rpx;
				height: 34rpx;
				background-color: #e4e7ed;
				position: absolute;
				left: -30rpx;
				top: 50%;
				transform: translateY(-50%);
			}
		}

		.head-subtitle {
			font-size: 26rpx;
			font-weight: 400;
			color: #c2c7cf;
			text-align: left;
			display: flex;
		}
	}

	.code-btn[disabled] {
		background-color: #fff;
	}

	.code-btn-start {
		width: 160rpx;
		line-height: 56rpx;
		border: 1rpx solid #e9b766;
		border-radius: 28rpx;
		font-size: 26rpx;
		font-weight: 400;
		color: #e9b766;
		opacity: 0.5;
	}

	.forgot-btn {
		width: 160rpx;
		line-height: 56rpx;
		font-size: 30rpx;
		font-weight: 500;
		color: #999;
	}

	.code-btn-end {
		opacity: 1 !important;
	}

	.login-btn-start {
		width: 158rpx;
		line-height: 56rpx;
		background: linear-gradient(90deg, #e9b461, #eecc89);
		border-radius: 28rpx;
		font-size: 26rpx;
		font-weight: 500;
		color: #ffffff;
	}

	.type-btn {
		padding: 20rpx;
		margin: 40rpx auto;
		width: 200rpx;
		font-size: 30rpx;
		font-weight: 500;
		color: #999999;
	}

	.auto-login-box {
		width: 100%;

		.auto-login-img {
			width: 68rpx;
			height: 68rpx;
			border-radius: 50%;
			margin: 0 30rpx;
		}
	}

	.agreement-box {
		margin: 80rpx auto 0;

		.protocol-check {
			transform: scale(0.7);
		}

		.agreement-text {
			font-size: 26rpx;
			font-weight: 500;
			color: #999999;

			.tcp-text {
				color: #e9b562;
			}
		}
	}
}

// 修改密码
.editPwd-btn-box {
	.save-btn {
		width: 690rpx;
		line-height: 70rpx;
		background: linear-gradient(90deg, #e9b461, #eecc89);
		border-radius: 35rpx;
		font-size: 28rpx;
		font-weight: 500;
		color: #ffffff;
	}

	.forgot-btn {
		width: 690rpx;
		line-height: 70rpx;
		font-size: 28rpx;
		font-weight: 500;
		color: #999999;
	}
}
</style>
